package com.shirotest.utility;

import java.awt.image.BufferedImage;
import java.io.PrintWriter;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求输出工具类
 */
public class ResponseUtility {
	/**
	 * 以纯文本输出字符串
	 * @param response
	 * @param message
	 */
	public static void responseText(HttpServletResponse response, String message){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("text/plain");
		if(message != null && message.trim().length() > 0){
			try {
				response.setContentLength(message.getBytes("UTF-8").length);
				response.getWriter().append(message);
				response.getWriter().flush();
				response.getWriter().close();
			}catch (Exception e) {
				
			}
		}
	}
	
	/**
	 * 以JSON形式输出字符串
	 * @param response
	 * @param message
	 */
	public static void responseJson(HttpServletResponse response, String message){
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setContentType("application/json;charset=utf-8");
		if(message != null && message.trim().length() > 0){
			try {
				response.setContentLength(message.getBytes("utf-8").length);
				response.getWriter().append(message);
				response.getWriter().flush();
				response.getWriter().close();
			}catch (Exception e) {
				
			}
		}
	}
	
	/**
	 * 向页面输出图片信息
	 * @param response
	 * @param bufferedImage
	 */
	public static void responseImage(HttpServletResponse response,BufferedImage bufferedImage){
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		if(bufferedImage != null){
			try {
				response.setDateHeader("Expires", 0);
				response.setContentType("image/jpeg");
				ServletOutputStream outputStream = response.getOutputStream();
				ImageIO.write(bufferedImage, "jpeg", outputStream);
				outputStream.close();
			}catch (Exception e) {
				
			}
		}
	}
	
	/**
	 * 向页面输出HTML
	 * @param response
	 * @param bufferedImage
	 */
	public static void responseHTML(HttpServletResponse response,String html){
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		if(html != null){
			try {
				response.setContentType("text/html;charset=utf-8");
				response.setCharacterEncoding("UTF-8");
				PrintWriter writer = response.getWriter();
				writer.print(html);
				response.flushBuffer();
			}catch (Exception e) {
				
			}
		}
	}
	
	/**
	 * 重定向页面
	 * @param response
	 * @param url
	 */
	public static void sendRedirect(HttpServletResponse response,String location){
		try{
			response.sendRedirect(location);
		}catch(Exception e){
		}
	}
}
